package com.lzq.mq.nameserver.event.handler;

import com.alibaba.fastjson2.JSON;
import com.lzq.mq.common.coder.TcpMsg;
import com.lzq.mq.common.enums.NameServerEventCode;
import com.lzq.mq.common.event.EventBus;
import com.lzq.mq.common.event.model.Event;
import com.lzq.mq.nameserver.event.model.SlaveHeartBeatEvent;
import com.lzq.mq.nameserver.event.model.SlaveReplicationMsgAckEvent;
import com.lzq.mq.nameserver.event.model.StartReplicationEvent;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

@ChannelHandler.Sharable
public class MasterReplicationServerHandler extends SimpleChannelInboundHandler<TcpMsg> {

    private EventBus eventBus;

    public MasterReplicationServerHandler(EventBus eventBus) {
        this.eventBus = eventBus;
    }

    // 1.网络请求的接受
    // 2.事件发不起的实现 事件总线->event
    // 3.事件处理器的实现
    // 4.数据存储
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TcpMsg tcpMsg) throws Exception {

        int code = tcpMsg.getCode();
        byte[] body = tcpMsg.getBody();
        Event event = null;
        if (NameServerEventCode.START_REPLICATION.getCode() == code) {
            event = JSON.parseObject(body, StartReplicationEvent.class);
        } else if(NameServerEventCode.SLAVE_HEART_BEAT.getCode() == code) {
            event = new SlaveHeartBeatEvent();
        } else if(NameServerEventCode.SLAVE_REPLICATION_ACK_MSG.getCode() == code) {
            event = JSON.parseObject(body, SlaveReplicationMsgAckEvent.class);
        }
        event.setChannelHandlerContext(channelHandlerContext);
        eventBus.publish(event);
    }

    /**
     * 异常处理
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }

    /**
     * 断开连接处理
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
    }
}
